package com.elinkway.infinitemovies.ui.fragment;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.elinkway.infinitemovies.adapter.OnePointAdapter;
import com.elinkway.infinitemovies.async.RequestOnepointListTask;
import com.elinkway.infinitemovies.bean.OnePointDataBean;
import com.elinkway.infinitemovies.bean.OnePointItemBean;
import com.elinkway.infinitemovies.bigdata.BigDataConstants;
import com.elinkway.infinitemovies.selfdata.MyDataRecordCreater;
import com.elinkway.infinitemovies.selfdata.bean.MyDataRecord;
import com.elinkway.infinitemovies.selfdata.bean.OnePointRecord;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;
import com.elinkway.infinitemovies.utils.ReportUtil;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.elinkway.infinitemovies.utils.UmengEventPoster;
import com.elinkway.infinitemovies.view.BaseRecyclerFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by lxj on 2017/8/23.
 */
public class OnePointFragment extends BaseRecyclerFragment {

    public static final String TAG = "OnePointFragment";

    private PullAndDownListener mPullAndDownListener;

    private RequestOnepointListTask mOnePointListTask;

    private ArrayList mAllItemList;

    private OnePointAdapter mOnePointAdapter;
    private final String ACTION_REFESH = "refesh";
    private final String ACTION_PAGEDOWN = "page_down";
    private static String from;   //跳转来源
    private long startTime;
    private LoadMoreEventDetector scrollListener=new ScrollListener();
    private long mOldShowTime = 0;
    private boolean isFirstShow=true;
    private boolean isVisible = false;
    protected boolean isCreated = false;
    private String pageid;
    private int start=0,end=0;


    private OnePointDataBean mResult;

    //判断是否为第一次请求  第一次请求才上报热门tab点击事件的pagestart方法（只有请求成功才有userid  上拉下拉请求不能多次上报热门点击）
    private boolean firstRequest=true;

    public static OnePointFragment newInstance(int position) {
        OnePointFragment fragment = new OnePointFragment();
        Bundle args = new Bundle();
        //说明是首页点击tab来的
        if (position==2) from="remen";
        if (position==3) from="push";
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isCreated = true;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPullAndDownListener = new PullAndDownListener();
        setPullListener(mPullAndDownListener);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mOnePointListTask = new RequestOnepointListTask(getActivity(), new OnePointListener(ACTION_REFESH));
        mOnePointListTask.start();
        showReport();
        startTime=System.currentTimeMillis();
        int actionBarHeight = 0;
        View view = super.onCreateView(inflater, container, savedInstanceState);
        Rect frame = new Rect();
        getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        if (getActivity() != null && getActivity() instanceof AppCompatActivity) {
            actionBarHeight = ((AppCompatActivity) getActivity()).getSupportActionBar().getHeight();
        }
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        lp.setMargins(0, actionBarHeight, 0, 0);
        mBaseRllayout.setLayoutParams(lp);
        return view;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isVisible = !hidden;
        if(hidden){
            pageEnd();
        } else {
            startTime=System.currentTimeMillis();
            pageStart(true);
            //切换tab曝光上报
            videoShowReport(start,end);
            isVisible = true;
            if(mOldShowTime > 0){
                if(System.currentTimeMillis() - mOldShowTime > 1800000){
                    requestOnePointData(ACTION_REFESH);
                }
            }
            mOldShowTime = System.currentTimeMillis();
        }
    }

    private void pageEnd() {
        if (null!=mResult&&!TextUtils.isEmpty(mResult.userid)){
            //上报：退出视频流
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("userid",mResult.userid);
                jsonObject.put("type", "QUIT");
                jsonObject.put("subType", "quitFeeds");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            ReportUtil.report(jsonObject);
            //上报：停留时长
            JSONObject timeObject = new JSONObject();
            try {
                if (null!=mAllItemList&&mAllItemList.size()>0){
                    timeObject.put("userid",mResult.userid);
                    timeObject.put("pageid",pageid);
                    timeObject.put("actionSrc", "list");
                    timeObject.put("fromid","u13746");
                    timeObject.put("subType","timeElapsed");
                    timeObject.put("srcType","1");
                    timeObject.put("timeElapsed",String.valueOf((System.currentTimeMillis() - startTime)/1000));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            ReportUtil.report(timeObject);
        }

        OnePointRecord record = MyDataRecordCreater.build(OnePointRecord.class);
        record.setResidenceTime(String.valueOf(System.currentTimeMillis() - startTime));
        record.setCur_url("VideoClips");
        RealmDaoManager.addMyDataRecord(record);
    }

    private void pageStart(boolean clicktab) {
        //上报：热门Tab点击
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("type","CLICK");
            jsonObject.put("subType","enterFeeds");
            //点击tab或者第一次页面请求成功上报
            if (null!=mResult&&(clicktab||firstRequest)){
                jsonObject.put("userid",mResult.userid);
                ReportUtil.report(jsonObject);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if (end>start){
            jsonReport(start,end);
        }
        if(isVisible){
            if(mOldShowTime > 0){
                if(System.currentTimeMillis() - mOldShowTime > 1800000){
                    requestOnePointData(ACTION_REFESH);
                }
            }
            mOldShowTime = System.currentTimeMillis();
        }
    }

    public void addOnScrollListener() {
        if (mRecyclerView != null && mLoadMoreEventDetector != null) {
            mRecyclerView.addOnScrollListener(scrollListener);
        }
    }

    //上报：热门短视频列表页展示
    private void showReport() {
        //上报：短视频页访问
        UmengEventPoster.doEventPost(BigDataConstants.PAGE_SHOW_VIDEOCLIPS);
        OnePointRecord record = MyDataRecordCreater.build(OnePointRecord.class);
        record.setFrom(from);
        record.setAcode("51");
        record.setCur_url("VideoClips");
        RealmDaoManager.addMyDataRecord(record);
    }

    private class PullAndDownListener extends PullListener {
        @Override
        public void requestMore() {
            super.requestMore();
            requestOnePointData(ACTION_PAGEDOWN);
        }

        @Override
        public void requestRefresh() {
            super.requestRefresh();
            requestOnePointData(ACTION_REFESH);
        }
    }

    class OnePointListener extends BasePullRequestListener<OnePointDataBean> {

        String action;

        public OnePointListener(String action){
            this.action = action;
        }

        @Override
        public boolean onRequestFailed() {
            if(mAllItemList == null || mAllItemList.size() == 0){
                RequestFailureReport();
                super.onRequestFailed();
            }else{
                lastRequestMoreSuccessed = true;
                if(mPullAndDownListener != null){
                    mPullAndDownListener.requestComplete();
                }
            }
            return false;
        }

        @Override
        public void onRequestSuccess(int updateId, OnePointDataBean result) {
            super.onRequestSuccess(updateId, result);
            mResult=result;
            //只有第一次请求成功才上报
            pageStart(false);
            firstRequest=false;
            RequestSuccessReport();
            if(result != null){
                if(result.itemBeanList!= null && result.itemBeanList.size() > 0){
                    setData(result, action);
                }else {
                    ToastUtil.showShortToast(getActivity(), "暂无更多新内容");
                }
            }
        }

        @Override
        public void onPreRequest() {
            //上报：短视频内容请求
            UmengEventPoster.doEventPost(BigDataConstants.YDZX_REQUEST);
        }
    }

    //上报：接口请求成功
    private void RequestSuccessReport() {
        OnePointRecord record = MyDataRecordCreater.build(OnePointRecord.class);
        record.setAcode("52");
        record.setCur_url("VideoClips");
        RealmDaoManager.addMyDataRecord(record);
    }

    //上报：接口请求失败
    private void RequestFailureReport() {
        OnePointRecord record = MyDataRecordCreater.build(OnePointRecord.class);
        record.setAcode("22");
        record.setCur_url("VideoClips");
        record.setResult("0");
        RealmDaoManager.addMyDataRecord(record);
    }


    private void requestOnePointData(String action){
        if (mOnePointListTask != null) {
            if (!mOnePointListTask.isCancelled()) {
                mOnePointListTask.cancel();
                mOnePointListTask = null;
            }
        }
        mOnePointListTask = new RequestOnepointListTask(getActivity(), new OnePointListener(action));
        mOnePointListTask.setAction(action);
        if(mAllItemList != null){
            mOnePointListTask.setHistorycount(mAllItemList.size());
        }
        mOnePointListTask.start();
    }

    private void setData(OnePointDataBean result, String aciton) {
        OnePointRecord record = MyDataRecordCreater.build(OnePointRecord.class);
        if(ACTION_REFESH.equals(aciton)){
            record.setAcode("21");
            mAllItemList = result.itemBeanList;
            pageid = result.itemBeanList.get(0).pageid;
            mAllItemList.add(0, "推荐了"+ result.itemBeanList.size() +"条新内容");
            mOnePointAdapter = new OnePointAdapter(getActivity(), mAllItemList);
            mOnePointAdapter.setUserid(result.userid);
            mOnePointAdapter.setFromid(result.fromid);
            setLayoutManager(new LinearLayoutManager(getActivity()));
            setAdapter(mOnePointAdapter);
            new android.os.Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mOnePointAdapter.notifyItemRemoved(0);
                    mAllItemList.remove(0);
                    isFirstShow=true;
                    videoShowReport(start,end);
                }
            }, 1500);
        }else{
            record.setAcode("22");
            mOnePointAdapter.notifyItemRangeInserted(mAllItemList.size(), result.itemBeanList.size());
            mAllItemList.addAll(result.itemBeanList);
        }
        record.setResult("1");
        record.setPiece(result.itemBeanList.size()+"");
        record.setCur_url("VideoClips");
        RealmDaoManager.addMyDataRecord(record);
    }

    @Override
    public void onPause() {
        pageEnd();
        super.onPause();
    }

    @Override
    public void onStop() {

        super.onStop();
    }
    public class ScrollListener extends LoadMoreEventDetector{
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if(newState == RecyclerView.SCROLL_STATE_IDLE){
                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                LinearLayoutManager linearManager = (LinearLayoutManager) manager;
                start=linearManager.findFirstCompletelyVisibleItemPosition();
                end=linearManager.findLastCompletelyVisibleItemPosition();
                videoShowReport(start,end);
            }
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (isFirstShow){
                isFirstShow=false;
                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                LinearLayoutManager linearManager = (LinearLayoutManager) manager;
                start=linearManager.findFirstCompletelyVisibleItemPosition();
                end=linearManager.findLastCompletelyVisibleItemPosition();
                videoShowReport(start,end);
            }
            super.onScrolled(recyclerView, dx, dy);
        }
    }
    //上报：短视频内容消费（展示）
    private void videoShowReport(int start,int end) {
        //上报：一点资讯(合作方)视频曝光
        jsonReport(start, end);
        for (int i = start; i <=end ; i++) {
            MyDataRecord record = MyDataRecordCreater.build(MyDataRecord.class);
            record.setAcode("41");
            record.setCur_url("VideoClips");
            RealmDaoManager.addMyDataRecord(record);
        }
    }

    //上报：一点资讯(合作方)视频曝光
    private void jsonReport(int start, int end) {
        if (null==mAllItemList) return;
        JSONObject jsonObject=new JSONObject();
        try {
            JSONArray doc=new JSONArray();
            JSONObject one=new JSONObject();
            JSONArray docids=new JSONArray();

        String firtImpid="";
        if(start >= 0 && start < mAllItemList.size() && mAllItemList.get(start) instanceof OnePointItemBean){
            firtImpid = ((OnePointItemBean)mAllItemList.get(start)).impid;
        }
        OnePointItemBean item = null;
        for (int i = start; i <=end ; i++) {
            if(i >= 0 && i < mAllItemList.size() && mAllItemList.get(i) instanceof OnePointItemBean){
                item = (OnePointItemBean) mAllItemList.get(i);
                if (firtImpid.equals(item.impid)){
                    one.put("impid",firtImpid);
                    docids.put(item.docid);
                    //最后一个impid
                    if (i==end){
                        one.put("docids",docids);
                        doc.put(one);
                    }
                }else {
                    firtImpid=item.impid;
                    one.put("docids",docids);
                    doc.put(one);
                    one=new JSONObject();
                    docids=new JSONArray();
                }
            }
        }

            jsonObject.put("userid",mResult.userid);
            jsonObject.put("subType","expose");
            jsonObject.put("doc",doc);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ReportUtil.report(jsonObject);
    }
}
